#简单的tcp聊天测试脚本
from socket import *
from threading import Thread

def recvMsg(clientSocket, clientInfo):

    while True: 

        recvData = clientSocket.recv(1024)

        if len(recvData) <= 0:
            clientSocket.close()
            break
        if recvData.decode() == 'exit':
            clientSocket.close()
            break

        print("\n>>%s"%recvData.decode())

def sendMsg(clientSocket):

    while True:

        msg = input("<<")

        if msg != 'exit':
            clientSocket.send(msg.encode())
        else:
            clientSocket.send(msg.encode())
            clientSocket.close()
            break

def main():

    tcpSocket = socket(AF_INET, SOCK_STREAM)
    tcpSocket.bind(("", 8889))
    tcpSocket.listen(5)

    while True:
        print("等待客户端连接中。。。。")
        clientSocket, clientInfo = tcpSocket.accept()

        tr = Thread(target = recvMsg, args = (clientSocket, clientInfo))
        ts = Thread(target = sendMsg, args = (clientSocket,))

        tr.start()
        ts.start()

        tr.join()
        ts.join()

        break

    tcpSocket.close()

if __name__ == '__main__':
    main()
